package com.itheima.user.service;

import com.itheima.user.api.UserServiceApi;
import com.itheima.user.dao.UserMapper;
import com.itheima.user.model.User;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@Service
public class UserService implements UserServiceApi {

    @Autowired
    UserMapper userMapper;

    @Autowired
    StringRedisTemplate stringRedisTemplate;


    @Override
    public Map<String, Object> reister(User user, String code) {
        Optional<User> optional = Optional.ofNullable(user);
        Map<String, Object> resultMap = new HashMap<>();
        if (!optional.isPresent()) {
            resultMap.put("message", "用户信息不能为空!");
            return resultMap;
        }
        if (StringUtils.isEmpty(code)) {
            resultMap.put("message", "验证码不能为空!");
            return resultMap;
        }

        String codeEx = stringRedisTemplate.boundValueOps(user.getPhone()).get();

        if (StringUtils.isEmpty(codeEx)) {
            resultMap.put("message", "验证码已过期！");
            return resultMap;
        }
        if (!code.equals(codeEx)) {
            resultMap.put("message", "验证码不正确!");
            return resultMap;
        }
        user.setCreateTime(new Date());
        userMapper.insert(user);
        resultMap.put("message", "注册成功！");
        return resultMap;
    }

    @Override
    public Map<String, Object> login(User user, String code) {
        Optional<User> optional = Optional.ofNullable(user);
        Map<String, Object> resultMap = new HashMap<>();
        if (!optional.isPresent()) {
            resultMap.put("message", "用户信息不能为空!");
            return resultMap;
        }

        String codeEx = stringRedisTemplate.boundValueOps(user.getPhone()).get();

        if (StringUtils.isEmpty(codeEx)) {
            resultMap.put("message", "验证码已过期！");
            return resultMap;
        }
        if (!code.equals(codeEx)) {
            resultMap.put("message", "验证码不正确!");
            return resultMap;
        }
        resultMap.put("message","登录成功！");
        return resultMap;
    }

    /**
     *   调用第三方接口 !
     * @param phone
     * @return
     */
    @Override
    public String getSmsCode(String phone) {


        return null;
    }
}
